﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.ComponentModel;

namespace Dycox.ComponentModel
{
    [Obsolete("this type is subject to remove soon.")]
    public class ModelSchema
    {
        Dictionary<string, ModelProperty> _properties;

        internal protected ModelSchema(XElement elt)
        {
            string value;
            Type type;

            value = elt.GetAttrString("type");
            type = Type.GetType(value);
            if (type == null)
                throw new InvalidOperationException("Type " + value + " not found.");

            value = elt.GetAttrString("displayName");
            if (!string.IsNullOrWhiteSpace(value))
                _displayName = value;

            _modelType = type;

            PropertyDescriptorCollection coll = TypeDescriptor.GetProperties(type);

            _properties = new Dictionary<string, ModelProperty>();
            foreach (var pelt in elt.Elements(ModelManager.ModelNamespace + "property"))
            {
                value = pelt.GetAttrString("name").TrimToNull();
                if (value == null)
                    throw new InvalidOperationException("Property must have a valid name.");

                PropertyDescriptor pd;
                pd = coll[value];
                if (pd == null)
                    throw new InvalidOperationException("Property " + value + " not defined by " + type.FullName);

                ModelProperty ps = CreateProperty(pelt, pd);
                _properties.Add(ps.Name, ps);
            }
        }

        protected virtual ModelProperty CreateProperty(XElement element, PropertyDescriptor property)
        {
            ModelProperty p = new ModelProperty(property, element);
            return p;
        }

        //public bool Typeless
        //{
        //    get { return _modelType == null; }
        //}

        public ICollection<ModelProperty> Properties
        {
            get
            {
                if (_properties == null)
                    throw new InvalidOperationException("Cannot get properties while in code generation mode.");

                return _properties.Values;
            }
        }

        public ModelProperty GetProperty(string name)
        {
            ModelProperty p;

            if (_properties.TryGetValue(name, out p))
                return p;
            else
                return null;
        }

        private Type _modelType;

        public Type ModelType
        {
            get { return _modelType; }
        }

        private string _displayName;

        public string DisplayName
        {
            get { return _displayName; }
        }

    }
}
